<?php

namespace app\jiyun\controller\warehouse;

use app\common\model\jiyun\warehouse\WarehouseModel;
use app\common\model\jiyun\warehouse\WarehouseRegionLocationModel;
use app\common\model\jiyun\warehouse\WarehouseRegionModel;
use app\common\model\admin\AccountModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\facade\Validate;
use think\facade\Db;

/**
 * 货架管理
 * @class WarehouseLocation
 * @package app\jiyun\controller\warehouse
 * @auth shirukun
 * @date 2024/11/25 14:49
 */
class WarehouseLocation extends Controller
{

    // 不过滤user_id
    public $check_user = false;

    /**
     * 货架管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        WarehouseRegionModel::mQuery()->layTable(function () {
            $this->title = lang('货架管理');
            // 公司列表
            if ($this->super) {
                $this->account_list = AccountModel::mk()->where(['status'=> 1])->column('title', 'id');
            }else{
                $this->account_list = [];
            }
            $this->pageDatas();
        }, function (QueryHelper $query) {
            // 关联仓库名称
            $query->with(['warehouseName']);

            // 数据列表搜索过滤
            $query->equal('account_id,warehouse_id,region_code')->like('region_name');
        });
    }

    protected function _index_page_filter(&$data){
        // 公司列表
        if ($this->super) {
            $account_list = AccountModel::mk()->where(['status' => 1])->column('title', 'id');
        }else{
            $account_list = [];
        }

        // 货架列表
        $shelves_type = WarehouseRegionModel::SHELVES_TYPE_SB();
        // 状态
        $status = WarehouseRegionModel::REGION_STATUS_SB();
        // 层级显示
        $show_tier = WarehouseRegionModel::SHOW_TIER();

        foreach ($data as &$item) {
            $item['company_name'] = $account_list[$item['account_id']] ?? "-";
            $item['shelves_type'] = $shelves_type[$item['shelves_type']] ?? "-";
            $item['status'] = $status[$item['status']] ?? "-";
            $item['show_tier'] = $show_tier[$item['show_tier']] ?? "-";
        }
    }


    /**
     * 添加
     * @auth true
     */
    public function add()
    {
        if($this->request->isPost()){
            $data = $this->request->param();
            $rule = [
                "warehouse_id|".lang('仓库')    =>  "require",
                "region_name|".lang('区域名称')    =>  "require|length:1,50",
                "region_code|".lang('区域编码')    =>  "require|length:1,30",
                "connector|".lang('货位连接符')    =>  "require|length:1,4",
                "shelves_num|".lang('货架数量')    =>  "require|number|length:1,10",
                "shelves_origin_num|".lang('货架起始数')    =>  "require|number|length:1,4",
                "layers_num|".lang('层数')    =>  "require|number|length:1,10",
                "layers_origin_num|".lang('层数起始数')    =>  "require|number|length:1,4",
                "lattice_num|".lang('格数')    =>  "require|number|length:1,10",
                "lattice_origin_num|".lang('格数起始数')    =>  "require|number|length:1,4",
                "inventory_capacity|".lang('库存容量')    =>  "require|float|length:1,8",
                "sort|".lang('排序')    =>  "number|length:1,4",
                "shelves_type|".lang('货架类型')    =>  "require|in:10,20,30",
                "show_tier|".lang('层级显示')    =>  "require|in:10,20",
                "status|".lang('状态')    =>  "require|in:10,20",
            ];
            // 定验证规则
            $validate = Validate::rule($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            // 公司id
            $data['account_id'] = WarehouseModel::mk()->where(['id'=>$data['warehouse_id']])->value('account_id');

            // 检测区域编码是否重复
            $info = WarehouseRegionModel::mk()->where(['warehouse_id' => $data['warehouse_id'], 'region_code' => $data['region_code']])->find();
            if($info) {
                $this->error(lang('所选仓库下已存在【{:n1}】区域编码', ['n1' => $data['region_code']]));
            }

            try {
                // 开启事务
                Db::startTrans();

                // 写入货区货架
                $region_id = WarehouseRegionModel::mk()->strict(false)->insertGetId($data);
                // 生成货位
                $locations = $this->createLocations($data,$region_id);
                // 写入货位
                WarehouseRegionLocationModel::insertAll($locations);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error(lang('失败：') . $e->getMessage());
            }

            sysoplog('仓库中心', '添加货区货架');
            $this->success(lang('操作成功'));
        }

        $this->pageDatas();
        return $this->fetch('form',[
            'status'=>$this->status,
            'shelves_type'=>$this->shelves_type,
            'warehouse'=>$this->warehouse
        ]);
    }

    /**
     * 编辑
     * @auth true
     */
    public function edit()
    {
        if($this->request->isPost()){
            $data = $this->request->param();

            $rule = [
                "warehouse_id|".lang('仓库')    =>  "require",
                "region_name|".lang('区域名称')    =>  "require|length:1,50",
                "region_code|".lang('区域编码')    =>  "require|length:1,30",
                "connector|".lang('货位连接符')    =>  "require|length:1,4",
                "shelves_num|".lang('货架数量')    =>  "require|number|length:1,10",
                "shelves_origin_num|".lang('货架起始数')    =>  "require|number|length:1,4",
                "layers_num|".lang('层数')    =>  "require|number|length:1,10",
                "layers_origin_num|".lang('层数起始数')    =>  "require|number|length:1,4",
                "lattice_num|".lang('格数')    =>  "require|number|length:1,10",
                "lattice_origin_num|".lang('格数起始数')    =>  "require|number|length:1,4",
                "inventory_capacity|".lang('库存容量')    =>  "require|float|length:1,8",
                "sort|".lang('排序')    =>  "number|length:1,4",
                "shelves_type|".lang('货架类型')    =>  "require|in:10,20,30",
                "show_tier|".lang('层级显示')    =>  "require|in:10,20",
                "status|".lang('状态')    =>  "require|in:10,20",
            ];

            // 定验证规则
            $validate = Validate::rule($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            // 公司id
            $data['account_id'] = WarehouseModel::mk()->where(['id'=>$data['warehouse_id']])->value('account_id');

            // 检测区域编码是否重复
            $info = WarehouseRegionModel::mk()->whereNotIn('id', $data['id'])->where(['warehouse_id' => $data['warehouse_id'], 'region_code' => $data['region_code']])->find();
            if($info) {
                $this->error(lang('所选仓库下已存在【{:n1}】区域编码', ['n1' => $data['region_code']]));
            }

            try {
                // 开启事务
                Db::startTrans();

                // 更新货区
                WarehouseRegionModel::mk()->strict(false)->update($data);
                // 删除货位
                WarehouseRegionLocationModel::mk()->where('region_id', $data['id'])->delete();
                // 生成货位
                $locations = $this->createLocations($data,$data['id']);
                // 插入货位
                WarehouseRegionLocationModel::insertAll($locations);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error(lang('失败：') . $e->getMessage());
            }

            sysoplog('仓库中心', '编辑货区货架');
            $this->success(lang('操作成功'));
        }
        $this->pageDatas();
        $vo = WarehouseRegionModel::where('id',input('id'))->find();
        return $this->fetch('form',[
            'vo'=>$vo,
            'status'=>$this->status,
            'shelves_type'=>$this->shelves_type,
            'warehouse'=>$this->warehouse
        ]);
    }

    /**
     * 查看
     */
    public function locationIndex()
    {
        WarehouseRegionLocationModel::mQuery()->layTable(function () {
            $this->ids = input('id');
        }, function (QueryHelper $query) {
            $query->where(['region_id'=>input('id')]);
            $query->withAttr('shelves_type', function($value, $data) {
                $status = WarehouseRegionModel::SHELVES_TYPE_SB();
                return $status[$value] ?? "-";
            });
            // 数据列表搜索过滤
            $query->with(['warehouseName']);
            $query->like('location_code');
        });
    }

    /**
     * 货位编辑
     * @auth true
     */
    public function location_edit(){
        $this->pageDatas();
        WarehouseRegionLocationModel::mForm('location_edit');
    }

    /**
     * 删除货区货架
     * @auth true
     */
    public function remove()
    {
        WarehouseRegionLocationModel::where('region_id', 'in',input('id'))->delete();
        WarehouseRegionModel::mDelete();
    }


    /**
     * 生成货位
     */
    function createLocations($data,$id): array
    {
        // 不显示层级
        $data['show_tier'] != 20 ?: $data['layers_num'] = 1;

        $locations = [];
        $k = 0;
        for ($i = 1; $i <= $data['shelves_num']; $i++) {
            for ($y = 1; $y <= $data['layers_num']; $y++) {
                for ($x = 1; $x <= $data['lattice_num']; $x++) {
                    $shelves_code = ($data['shelves_origin_num']-1) + $i;
                    $layers_num = ($data['layers_origin_num']-1) + $y;
                    $lattice_num = ($data['lattice_origin_num']-1) + $x;
                    $location['account_id'] = $data['account_id'];
                    $location['warehouse_id'] = $data['warehouse_id'];
                    $location['region_id'] = $id;
                    $location['region_code'] = $data['region_code'];
                    $location['shelves_code'] = $shelves_code;
                    $location['layers_num'] = $layers_num;
                    $location['lattice_num'] = $lattice_num;
                    if($data['show_tier'] == 20){ // 显示层级
                        $location['location_code'] = $data['region_code'] . $shelves_code . $data['connector'] . $layers_num . $data['connector'] . $lattice_num;
                    }else{ // 不显示层级
                        $location['location_code'] = $data['region_code'] . $shelves_code . $data['connector'] .  $lattice_num;
                    }
                    $location['sort'] = ++$k;
                    $location['status'] = $data['status'];
                    $location['shelves_type'] = $data['shelves_type'];
                    $location['inventory_capacity'] = $data['inventory_capacity'];
                    array_push($locations, $location);
                }
            }
        }
        return $locations;
    }

    //页面需要的数据
    private function pageDatas(){

        $this->status = WarehouseRegionModel::REGION_STATUS_SB();//状态
        $this->shelves_type = WarehouseRegionModel::SHELVES_TYPE_SB();//货架类型
        $this->show_tier = WarehouseRegionModel::SHOW_TIER();//层级显示
        // 仓库列表
        if ($this->super) {
            $this->warehouse = WarehouseModel::mk()->where(['status'=>1])->column('warehouse_c_name', 'id');
        }else{
            $this->warehouse = WarehouseModel::mk()->where(['account_id'=>$this->adminUser['account_id'],'status'=>1])->column('warehouse_c_name', 'id');
        }
    }

    /**
     * 按货区打印
     * @auth true
     */
    public function print_region()
    {

        $id = input('id');
        // 货位
        $data = WarehouseRegionLocationModel::mq()->where(['region_id'=>$id])->field('location_code')->select()->toArray();
//        halt($data);

        $this->success(lang('数据获取成功'), ['jsonData'=>$data]);
    }

    /**
     * 按货位打印
     * @auth true
     */
    public function print_location()
    {

        $id = input('id');
        // 货位
        $data = WarehouseRegionLocationModel::mq()->where(['id'=>$id])->field('location_code')->select()->toArray();
//        halt($data);

        $this->success(lang('数据获取成功'), ['jsonData'=>$data]);
    }
}